package com.dbq.fast.business.me.api;

import com.dbq.fast.business.login.api.LoginApi;
import com.dbq.fast.business.product.api.CommonTransformer;
import com.dbq.fast.common.bean.User;
import com.dbq.fast.common.net.HttpManager;
import com.dbq.fast.common.net.RemoteApiCallBack;

import java.util.HashMap;

/**
 * 账户管理API
 */
public class AccountManagerAPI {

    private static HttpManager httpManager = HttpManager.getInstance();

    /***
     * 获取邮箱验证码
     * @param c
     * @param email
     */
    public static void requestEmailVerifiCode(RemoteApiCallBack<String> c,String email){
        String account = User.getInstance().getAccount();
        String token = User.getInstance().getToken();
        httpManager.getHttpService()
                .requestEmailVerifiCode(token,email, account)
                .compose(new CommonTransformer<>())
                .subscribe(result -> {
                    if(result.isSuccess()){
                        c.onSuccess("success");
                    }else if(result.getCode() == 401){
                        new Thread(()->{
                            String newToken = LoginApi.refreshTokenSync(true);
                            if ("".equals(newToken)) return;
                            requestEmailVerifiCode(c, email);
                        }).start();

                    }else {
                        c.onFail(result.getCode(),result.getMsg());
                    }
                }, throwable -> {
                    c.onFail(-1000,"error");
                });
    }

    /***
     * 绑定邮箱
     * @param c
     * @param email
     * @param captcha
     */
    public static void bindEmail(RemoteApiCallBack<String> c,String email,String captcha){
        String account = User.getInstance().getAccount();
        String token = User.getInstance().getToken();
        HashMap params = new HashMap();
        params.put("email",email);
        params.put("account",account);
        params.put("captcha",captcha);
        httpManager.getHttpService()
                .bindEmail(token,params)
                .compose(new CommonTransformer<>())
                .subscribe(result -> {
                    if(result.isSuccess()){
                        c.onSuccess("success");
                    }else if(result.getCode() == 401){
                        new Thread(()->{
                            String newToken = LoginApi.refreshTokenSync(true);
                            if ("".equals(newToken)) return;
                            bindEmail(c, email, captcha);
                        }).start();

                    }else {
                        c.onFail(result.getCode(),result.getMsg());
                    }
                }, throwable -> {
                    c.onFail(-1000,"error");
                });
    }
}
